<template>
  <div class="campaign-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>营销活动管理</span>
          <div class="header-operations">
            <el-button type="primary" @click="handleAdd">创建活动</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
        <el-form-item label="活动类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择活动类型" clearable>
            <el-option
              v-for="item in campaignTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择活动状态" clearable>
            <el-option
              v-for="item in campaignStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间" prop="timeRange">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="搜索关键词" prop="keyword">
          <el-input
            v-model="queryParams.keyword"
            placeholder="活动名称/活动编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 活动统计卡片 -->
      <el-row :gutter="20" class="statistics-cards">
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>进行中活动</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">{{ statistics.ongoingCount }}</div>
              <div class="label">个</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>待开始活动</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">{{ statistics.pendingCount }}</div>
              <div class="label">个</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>已结束活动</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">{{ statistics.endedCount }}</div>
              <div class="label">个</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>参与人数</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">{{ statistics.totalParticipants }}</div>
              <div class="label">人</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 活动列表 -->
      <el-table
        v-loading="loading"
        :data="campaignList"
        style="width: 100%"
        border
      >
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="campaignNo" label="活动编号" width="120" />
        <el-table-column prop="name" label="活动名称" width="180" />
        <el-table-column prop="type" label="活动类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getCampaignTypeTag(row.type)">
              {{ getCampaignTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getCampaignStatusTag(row.status)">
              {{ getCampaignStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="participants" label="参与人数" width="100" />
        <el-table-column prop="budget" label="预算" width="120">
          <template #default="{ row }">
            ¥ {{ row.budget?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="actualCost" label="实际支出" width="120">
          <template #default="{ row }">
            ¥ {{ row.actualCost?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleDetail(row)"
            >
              详情
            </el-button>
            <el-button
              link
              type="success"
              @click="handleEdit(row)"
              v-if="row.status === 0"
            >
              编辑
            </el-button>
            <el-button
              link
              type="warning"
              @click="handlePublish(row)"
              v-if="row.status === 0"
            >
              发布
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleCancel(row)"
              v-if="row.status === 1"
            >
              取消
            </el-button>
            <el-button
              link
              type="info"
              @click="handleAnalysis(row)"
            >
              分析
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑活动对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '创建活动' : '编辑活动'"
      width="800px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择活动类型">
            <el-option
              v-for="item in campaignTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间" prop="timeRange">
          <el-date-picker
            v-model="form.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="活动预算" prop="budget">
          <el-input-number
            v-model="form.budget"
            :min="0"
            :precision="2"
            :step="1000"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="活动规则" prop="rules">
          <el-input
            v-model="form.rules"
            type="textarea"
            :rows="4"
            placeholder="请输入活动规则"
          />
        </el-form-item>
        <el-form-item label="活动说明" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入活动说明"
          />
        </el-form-item>
        <el-form-item label="活动海报" prop="poster">
          <el-upload
            class="poster-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="form.poster" :src="form.poster" class="poster" />
            <el-icon v-else class="poster-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 活动详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="活动详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="活动编号">{{ detail.campaignNo }}</el-descriptions-item>
        <el-descriptions-item label="活动名称">{{ detail.name }}</el-descriptions-item>
        <el-descriptions-item label="活动类型">
          <el-tag :type="getCampaignTypeTag(detail.type)">
            {{ getCampaignTypeLabel(detail.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="活动状态">
          <el-tag :type="getCampaignStatusTag(detail.status)">
            {{ getCampaignStatusLabel(detail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ detail.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ detail.endTime }}</el-descriptions-item>
        <el-descriptions-item label="活动预算">
          ¥ {{ detail.budget?.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="实际支出">
          ¥ {{ detail.actualCost?.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="参与人数">{{ detail.participants }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="活动规则" :span="2">{{ detail.rules }}</el-descriptions-item>
        <el-descriptions-item label="活动说明" :span="2">{{ detail.description }}</el-descriptions-item>
        <el-descriptions-item label="活动海报" :span="2">
          <el-image
            v-if="detail.poster"
            :src="detail.poster"
            :preview-src-list="[detail.poster]"
            fit="contain"
            style="width: 200px; height: 200px"
          />
          <span v-else>无</span>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 参与记录 -->
      <div class="detail-section">
        <div class="section-title">参与记录</div>
        <el-table :data="detail.participationRecords" border>
          <el-table-column prop="memberNo" label="会员号" width="120" />
          <el-table-column prop="memberName" label="会员姓名" width="120" />
          <el-table-column prop="phone" label="手机号" width="120" />
          <el-table-column prop="reward" label="获得奖励" width="120" />
          <el-table-column prop="participateTime" label="参与时间" width="180" />
          <el-table-column prop="remark" label="备注" />
        </el-table>
      </div>
    </el-dialog>

    <!-- 活动分析对话框 -->
    <el-dialog
      v-model="analysisDialogVisible"
      title="活动分析"
      width="1000px"
    >
      <el-tabs v-model="activeTab">
        <el-tab-pane label="参与趋势" name="trend">
          <div ref="trendChartRef" style="width: 100%; height: 400px"></div>
        </el-tab-pane>
        <el-tab-pane label="会员分析" name="member">
          <div ref="memberChartRef" style="width: 100%; height: 400px"></div>
        </el-tab-pane>
        <el-tab-pane label="效果分析" name="effect">
          <div ref="effectChartRef" style="width: 100%; height: 400px"></div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { 
  getCampaignList, 
  getCampaignStatistics,
  addCampaign,
  updateCampaign,
  publishCampaign,
  cancelCampaign,
  getCampaignDetail,
  getCampaignAnalysis
} from '@/api/marketing'

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  type: undefined,
  status: undefined,
  timeRange: [],
  keyword: ''
})

// 活动类型选项
const campaignTypes = [
  { label: '满减活动', value: 'DISCOUNT' },
  { label: '优惠券', value: 'COUPON' },
  { label: '积分活动', value: 'POINTS' },
  { label: '抽奖活动', value: 'LUCKY_DRAW' }
]

// 活动状态选项
const campaignStatus = [
  { label: '未开始', value: 0 },
  { label: '进行中', value: 1 },
  { label: '已结束', value: 2 },
  { label: '已取消', value: 3 }
]

// 统计数据
const statistics = ref({
  ongoingCount: 0,
  pendingCount: 0,
  endedCount: 0,
  totalParticipants: 0
})

// 上传地址
const uploadUrl = import.meta.env.VITE_API_URL + '/upload'

// 表格数据
const loading = ref(false)
const campaignList = ref([])
const total = ref(0)

// 新增/编辑对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = ref({
  name: '',
  type: '',
  timeRange: [],
  budget: 0,
  rules: '',
  description: '',
  poster: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ],
  timeRange: [
    { required: true, message: '请选择活动时间', trigger: 'change' }
  ],
  budget: [
    { required: true, message: '请输入活动预算', trigger: 'blur' }
  ],
  rules: [
    { required: true, message: '请输入活动规则', trigger: 'blur' }
  ]
}

// 详情对话框
const detailDialogVisible = ref(false)
const detail = ref({})

// 分析对话框
const analysisDialogVisible = ref(false)
const activeTab = ref('trend')
const trendChartRef = ref(null)
const memberChartRef = ref(null)
const effectChartRef = ref(null)
let trendChart = null
let memberChart = null
let effectChart = null

// 获取活动类型标签
const getCampaignTypeTag = (type) => {
  const map = {
    DISCOUNT: 'success',
    COUPON: 'warning',
    POINTS: 'info',
    LUCKY_DRAW: 'danger'
  }
  return map[type] || 'info'
}

// 获取活动类型标签文本
const getCampaignTypeLabel = (type) => {
  const item = campaignTypes.find(item => item.value === type)
  return item ? item.label : type
}

// 获取活动状态标签
const getCampaignStatusTag = (status) => {
  const map = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return map[status] || 'info'
}

// 获取活动状态标签文本
const getCampaignStatusLabel = (status) => {
  const item = campaignStatus.find(item => item.value === status)
  return item ? item.label : status
}

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getCampaignList(queryParams.value)
    campaignList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取活动列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const res = await getCampaignStatistics()
    statistics.value = res.data
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 查询按钮点击
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
  getStatistics()
}

// 重置按钮点击
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    type: undefined,
    status: undefined,
    timeRange: [],
    keyword: ''
  }
  handleQuery()
}

// 新增按钮点击
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    name: '',
    type: '',
    timeRange: [],
    budget: 0,
    rules: '',
    description: '',
    poster: ''
  }
  dialogVisible.value = true
}

// 编辑按钮点击
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = {
    id: row.id,
    name: row.name,
    type: row.type,
    timeRange: [row.startTime, row.endTime],
    budget: row.budget,
    rules: row.rules,
    description: row.description,
    poster: row.poster
  }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const [startTime, endTime] = form.value.timeRange
        const data = {
          ...form.value,
          startTime,
          endTime
        }
        delete data.timeRange

        if (dialogType.value === 'add') {
          await addCampaign(data)
          ElMessage.success('创建成功')
        } else {
          await updateCampaign(data)
          ElMessage.success('编辑成功')
        }
        dialogVisible.value = false
        handleQuery()
      } catch (error) {
        console.error(dialogType.value === 'add' ? '创建失败:' : '编辑失败:', error)
        ElMessage.error(dialogType.value === 'add' ? '创建失败' : '编辑失败')
      }
    }
  })
}

// 查看详情
const handleDetail = async (row) => {
  try {
    const res = await getCampaignDetail(row.id)
    detail.value = res.data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取活动详情失败:', error)
    ElMessage.error('获取活动详情失败')
  }
}

// 发布活动
const handlePublish = async (row) => {
  try {
    await ElMessageBox.confirm('确认发布该活动吗？', '提示', {
      type: 'warning'
    })
    
    await publishCampaign(row.id)
    ElMessage.success('发布成功')
    handleQuery()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发布失败:', error)
      ElMessage.error('发布失败')
    }
  }
}

// 取消活动
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm('确认取消该活动吗？', '提示', {
      type: 'warning'
    })
    
    await cancelCampaign(row.id)
    ElMessage.success('取消成功')
    handleQuery()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消失败:', error)
      ElMessage.error('取消失败')
    }
  }
}

// 活动分析
const handleAnalysis = async (row) => {
  try {
    const res = await getCampaignAnalysis(row.id)
    analysisDialogVisible.value = true
    await nextTick()
    initCharts(res.data)
  } catch (error) {
    console.error('获取活动分析数据失败:', error)
    ElMessage.error('获取活动分析数据失败')
  }
}

// 初始化图表
const initCharts = (data) => {
  // 参与趋势图
  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value)
  }
  trendChart.setOption({
    title: {
      text: '参与趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: data.trend.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: data.trend.counts,
      type: 'line',
      smooth: true
    }]
  })

  // 会员分析图
  if (!memberChart) {
    memberChart = echarts.init(memberChartRef.value)
  }
  memberChart.setOption({
    title: {
      text: '会员分析'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [{
      type: 'pie',
      radius: '50%',
      data: data.member.map(item => ({
        name: item.name,
        value: item.value
      }))
    }]
  })

  // 效果分析图
  if (!effectChart) {
    effectChart = echarts.init(effectChartRef.value)
  }
  effectChart.setOption({
    title: {
      text: '效果分析'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['预算', '实际支出', '参与人数']
    },
    xAxis: {
      type: 'category',
      data: data.effect.categories
    },
    yAxis: [
      {
        type: 'value',
        name: '金额',
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      {
        type: 'value',
        name: '人数',
        axisLabel: {
          formatter: '{value}人'
        }
      }
    ],
    series: [
      {
        name: '预算',
        type: 'bar',
        data: data.effect.budgets
      },
      {
        name: '实际支出',
        type: 'bar',
        data: data.effect.costs
      },
      {
        name: '参与人数',
        type: 'line',
        yAxisIndex: 1,
        data: data.effect.participants
      }
    ]
  })
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    form.value.poster = res.data.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error('上传失败')
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

// 监听标签页切换
watch(activeTab, (val) => {
  nextTick(() => {
    switch (val) {
      case 'trend':
        trendChart?.resize()
        break
      case 'member':
        memberChart?.resize()
        break
      case 'effect':
        effectChart?.resize()
        break
    }
  })
})

onMounted(() => {
  handleQuery()
})

onUnmounted(() => {
  trendChart?.dispose()
  memberChart?.dispose()
  effectChart?.dispose()
})
</script>

<style lang="scss" scoped>
.campaign-container {
  padding: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .statistics-cards {
    margin-bottom: 20px;
    
    .statistics-content {
      text-align: center;
      
      .amount {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin: 10px 0;
      }
      
      .label {
        font-size: 14px;
        color: #909399;
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .dialog-footer {
    text-align: right;
  }
  
  .poster-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      
      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }
  
  .poster-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 200px;
    text-align: center;
    line-height: 200px;
  }
  
  .poster {
    width: 200px;
    height: 200px;
    display: block;
  }
  
  .detail-section {
    margin-top: 20px;
    
    .section-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 10px;
      color: #303133;
    }
  }
}
</style> 